package cn.itcast.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

// @Order(0)
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取request
        ServerHttpRequest request = exchange.getRequest();

        // 2.获取请求参数 authorization
        MultiValueMap<String, String> params = request.getQueryParams();
        String authorization = params.getFirst("authorization");

        // 3.判断值是否为 admin
        if ("admin".equals(authorization)) {
            // 4.如果是，放行到下一个过滤器
            return chain.filter(exchange);
        }

        // 5.如果不是，则拦截请求
        ServerHttpResponse response = exchange.getResponse();
        // 5.1.设定http状态码，401，代表未登录
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 5.2.终止请求，返回结果
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
